<!--
  + fetch 只会有一次运行
    + 如果直接在地址栏输入/fetchState 或刷新本页面 则是在服务端运行(server) fetch和asyncData
    + 如果是已经在浏览器打开了其他页面，然后跳转到此页面（非打开新窗口），则是客户端 client
    + 如果是打开新窗口，则是服务端运行两个钩子（fetch和asyncData）
 -->
<template>
  <div>
    <p v-if="$fetchState.pending">
      Fetching mountains...
    </p>
    <p v-else-if="$fetchState.error">
      An error occurred :(
    </p>
    <div v-else>
      <h1>Nuxt Mountains</h1>
      <ul>
        <li v-for="(mountain, index) of mountains" :key="index">
          {{ mountain.title }}
        </li>
      </ul>
      <button @click="$fetch">
        Refresh
      </button>
    </div>
    <nuxt-link
      to="/"
      target="_blank"
    >
      index {{ renderedOn }}
    </nuxt-link>
  </div>
</template>

<script>
export default {
  asyncData () {
    let renderedOn = process.client ? 'client' : 'server'
    renderedOn += ',Created at: ' + new Date()
    // eslint-disable-next-line no-console
    console.log('Created at: ' + new Date(), renderedOn)
    return { renderedOn }
  },
  data () {
    return {
      mountains: []
    }
  },
  async fetch () {
    const renderedOn = process.client ? 'client' : 'server'
    // eslint-disable-next-line no-console
    console.log('fetchState', renderedOn)
    this.mountains = await fetch(
      'https://api.nuxtjs.dev/mountains'
    ).then(res => res.json())
  },
  activated () {
    // eslint-disable-next-line no-console
    console.log('fetchState 被激活', this.$fetchState.timestamp)
    // Call fetch again if last fetch more than 30 sec ago
    if (this.$fetchState.timestamp <= Date.now() - 30000) {
      this.$fetch()
    }
  }
}
</script>
